package com.rem.concurrency.juc.my3Pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 四个线程的 生产者和消费者
 * <p>
 * <p>
 * JUC 版本
 *
 * @author Rem
 * @date 2021-03-08
 */

public class C {

    public static void main(String[] args) {
        Data3 data = new Data3();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        }, "D").start();
    }
}

class Data3 {

    private int num = 0;
    private Lock lock = new ReentrantLock();

    //相当于 sycchronized版wait和notify
    Condition condition = lock.newCondition();

    /**
     * +1操作
     */
    void increment() {
        lock.lock();
        try {
            while (num != 0) {
                //不等于0 等待其他线程操作
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "==>" + num);
            //操作完毕 ，通知其他线程操作
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * -1操作
     */
    void decrement() {
        lock.lock();
        try {
            while (num == 0) {
                //等于0 等待其他线程操作
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "==>" + num);
            //操作完毕 ，通知其他线程操作
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

